package com.afd.ozblip.activity;

import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afd.ozblip.app.CommonInfo;
import com.afd.ozblip.entity.AddressEntity;
import com.afd.ozblip.net.HttpUtil;
import com.afd.ozblip.util.AsyncAction;
import com.afd.ozblip.util.AsyncLoadData;
import com.afd.ozblip.util.Constants;
import com.afd.ozblip.util.LocationUtil;
import com.afd.ozblip.util.ParseJson;

public class SearchFragment extends Fragment
{
	
	/****************** 视图变量 **************************/
	private LinearLayout choiceCityLayout;
	
	private LinearLayout meishiLayout;
	
	private LinearLayout xiaochiLayout;
	
	private LinearLayout kafeiLayout;
	
	private LinearLayout movieLayout;
	
	private LinearLayout shoppingLayout;
	
	private LinearLayout moreLayout;
	
	private LinearLayout nearbyPeopleLayout;
	
	private LinearLayout nearbyVipLayout;
	
	private LinearLayout searchAllLayout;
	
	private LinearLayout searchCouponLayout;
	
	private LinearLayout[] categoryLayoutArr;
	
	private TextView addressTv;
	
	private TextView cityTv;
	
	private EditText searchEt;
	
	/****************** 操作变量 **************************/
	private IndexActivity mActivity;
	
	private MyReceiver receiver;
	
	/****************** 数据变量 **************************/
	private AddressEntity addressObj;
	
	@Override
	public void onAttach(Activity activity)
	{
		super.onAttach(activity);
		try
		{
			mActivity = (IndexActivity) activity;
		}
		catch (ClassCastException e)
		{
			throw new ClassCastException("Activity 必须是 " + IndexActivity.class.getName());
		}
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		// 获取参数
		getBundle();
		receiver = new MyReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction("android.intent.action.MY_RECEIVER");
		// 注册
		mActivity.registerReceiver(receiver, filter);
		
		requestAreaListData();
		
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		final View rootView = inflater.inflate(R.layout.index_search_fragment, container, false);
		// 寻找视图
		findViews(rootView);
		// 设置监听
		setListeners();
		// 获取定位地址
		if (CommonInfo.commonLocation != null)
		{
			requestLocationData();
		}
		return rootView;
	}
	
	/**
	 * 寻找视图
	 */
	public void findViews(View rootView)
	{
		this.choiceCityLayout = (LinearLayout) rootView.findViewById(R.id.ll_index_choice_city);
		// 分类视图
		this.meishiLayout = (LinearLayout) rootView.findViewById(R.id.ll_index_class_meishi);
		this.xiaochiLayout = (LinearLayout) rootView.findViewById(R.id.ll_index_class_xiaochi);
		this.kafeiLayout = (LinearLayout) rootView.findViewById(R.id.ll_index_class_kafei);
		this.movieLayout = (LinearLayout) rootView.findViewById(R.id.ll_index_class_movie);
		this.shoppingLayout = (LinearLayout) rootView.findViewById(R.id.ll_index_class_shopping);
		this.moreLayout = (LinearLayout) rootView.findViewById(R.id.ll_index_class_more);
		categoryLayoutArr = new LinearLayout[6];
		categoryLayoutArr[0] = meishiLayout;
		categoryLayoutArr[1] = xiaochiLayout;
		categoryLayoutArr[2] = kafeiLayout;
		categoryLayoutArr[3] = movieLayout;
		categoryLayoutArr[4] = shoppingLayout;
		categoryLayoutArr[5] = moreLayout;
		
		this.nearbyPeopleLayout = (LinearLayout) rootView.findViewById(R.id.ll_index_nearby_people);
		this.nearbyVipLayout = (LinearLayout) rootView.findViewById(R.id.ll_index_nearby_vip);
		this.searchAllLayout = (LinearLayout) rootView.findViewById(R.id.ll_index_search_all);
		this.searchCouponLayout = (LinearLayout) rootView.findViewById(R.id.ll_index_search_coupon);
		this.addressTv = (TextView) rootView.findViewById(R.id.tv_index_location_address);
		this.cityTv = (TextView) rootView.findViewById(R.id.tv_index_location_city);
		this.searchEt = (EditText) rootView.findViewById(R.id.et_index_search);
	}
	
	@Override
	public void onDestroy()
	{
		super.onDestroy();
		// 不要忘了这一步
		mActivity.unregisterReceiver(receiver);
	}
	
	@Override
	public void onResume()
	{
		super.onResume();
		// 设置当前定位城市
		setViews();
	}
	
	/**
	 * 设置监听
	 */
	public void setListeners()
	{
		View.OnClickListener searchClick = new View.OnClickListener()
		{
			
			@Override
			public void onClick(View v)
			{
				switch (v.getId())
				{
					case R.id.ll_index_choice_city:
						Intent cityIntent = new Intent(mActivity, CityListActivity.class);
						startActivity(cityIntent);
						break;
					case R.id.ll_index_class_meishi:
						// 判断是否是当前城市
						if (isNowCity())
						{
							// 改变分类背景
							changeClassBg(0);
							Intent meishiIntent = new Intent(mActivity, NearbyBusinessActivity.class);
							meishiIntent.putExtra("parentClassName", "美食");
							meishiIntent.putExtra("childClassName", "");
							startActivity(meishiIntent);
						}
						break;
					case R.id.ll_index_class_xiaochi:
						// 判断是否是当前城市
						if (isNowCity())
						{
							// 改变分类背景
							changeClassBg(1);
							Intent xiaochiIntent = new Intent(mActivity, NearbyBusinessActivity.class);
							xiaochiIntent.putExtra("parentClassName", "美食");
							xiaochiIntent.putExtra("childClassName", "快餐");
							startActivity(xiaochiIntent);
						}
						break;
					case R.id.ll_index_class_kafei:
						// 判断是否是当前城市
						if (isNowCity())
						{
							// 改变分类背景
							changeClassBg(2);
							Intent kafeiIntent = new Intent(mActivity, NearbyBusinessActivity.class);
							kafeiIntent.putExtra("parentClassName", "休闲娱乐");
							kafeiIntent.putExtra("childClassName", "咖啡厅");
							startActivity(kafeiIntent);
						}
						break;
					case R.id.ll_index_class_movie:
						// 判断是否是当前城市
						if (isNowCity())
						{
							// 改变分类背景
							changeClassBg(3);
							Intent movieIntent = new Intent(mActivity, NearbyBusinessActivity.class);
							movieIntent.putExtra("parentClassName", "休闲娱乐");
							movieIntent.putExtra("childClassName", "电影院");
							startActivity(movieIntent);
						}
						break;
					case R.id.ll_index_class_shopping:
						// 判断是否是当前城市
						if (isNowCity())
						{
							// 改变分类背景
							changeClassBg(4);
							Intent shoppingIntent = new Intent(mActivity, NearbyBusinessActivity.class);
							shoppingIntent.putExtra("parentClassName", "购物");
							shoppingIntent.putExtra("childClassName", "商场");
							startActivity(shoppingIntent);
						}
						break;
					case R.id.ll_index_class_more:
						// 判断是否是当前城市
						if (isNowCity())
						{
							// 改变分类背景
							changeClassBg(5);
							Intent moreIntent = new Intent(mActivity, MoreClassActivity.class);
							startActivity(moreIntent);
						}
						break;
					case R.id.ll_index_nearby_people:
						// 判断是否是当前城市
						if (isNowCity())
						{
							Intent peopleIntent = new Intent(mActivity, NearbyPeopleActivity.class);
							startActivity(peopleIntent);
						}
						break;
					case R.id.ll_index_nearby_vip:
						Intent vipIntent = new Intent(mActivity, NearbyVipActivity.class);
						startActivity(vipIntent);
						break;
					case R.id.ll_index_search_all:
						Intent allIntent = new Intent(mActivity, SearchAllActivity.class);
						startActivity(allIntent);
						break;
					case R.id.ll_index_search_coupon:
						Intent couponIntent = new Intent(mActivity, CouponActivity.class);
						startActivity(couponIntent);
						break;
					
					default:
						break;
				}
			}
		};
		this.choiceCityLayout.setOnClickListener(searchClick);
		this.meishiLayout.setOnClickListener(searchClick);
		this.xiaochiLayout.setOnClickListener(searchClick);
		this.kafeiLayout.setOnClickListener(searchClick);
		this.movieLayout.setOnClickListener(searchClick);
		this.shoppingLayout.setOnClickListener(searchClick);
		this.moreLayout.setOnClickListener(searchClick);
		this.nearbyPeopleLayout.setOnClickListener(searchClick);
		this.nearbyVipLayout.setOnClickListener(searchClick);
		this.searchAllLayout.setOnClickListener(searchClick);
		this.searchCouponLayout.setOnClickListener(searchClick);
		this.searchEt.setOnEditorActionListener(new TextView.OnEditorActionListener()
		{
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
			{
				String searchStr = searchEt.getText().toString();
				Intent searchIntent = new Intent(mActivity, BusinessSearchActivity.class);
				searchIntent.putExtra("searchStr", searchStr);
				startActivity(searchIntent);
				return false;
			}
		});
	}
	
	/**
	 * 判断是否是当前定位城市
	 */
	private boolean isNowCity()
	{
		if (!CommonInfo.commonIsNowCity())
		{
			// 您当前选择的城市是北京，如需使用附近功能，请切换至重庆
			final AlertDialog alertDialog = new AlertDialog.Builder(mActivity)
					.setTitle("提示")
					.setMessage(
							"您当前选择的城市是" + CommonInfo.commonNowCityName + "，如需使用附近功能，请切换至"
									+ CommonInfo.commonLocationCityName + "！").setIcon(android.R.drawable.ic_menu_help)
					.setNegativeButton("确定", new DialogInterface.OnClickListener()
					{
						
						@Override
						public void onClick(DialogInterface dialog, int which)
						{
							
						}
					}).create();
			alertDialog.show();
			return false;
		}
		return true;
	}
	
	private void changeClassBg(int index)
	{
		int len = categoryLayoutArr.length;
		for (int i = 0; i < len; i++)
		{
			if (i == index)
			{
				categoryLayoutArr[i].setBackgroundColor(getResources().getColor(R.color.index_color_bg2));
				TextView classTv = (TextView) categoryLayoutArr[i].getChildAt(1);
				classTv.setBackgroundResource(R.drawable.index_selected_bg);
				classTv.setTextColor(getResources().getColor(R.color.white));
			}
			else
			{
				categoryLayoutArr[i].setBackgroundColor(getResources().getColor(R.color.transparent));
				TextView classTv = (TextView) categoryLayoutArr[i].getChildAt(1);
				classTv.setBackgroundResource(R.color.transparent);
				classTv.setTextColor(getResources().getColor(R.color.index_class_text));
			}
		}
		
	}
	
	/**
	 * 获取传递的参数
	 */
	private void getBundle()
	{
		// Intent intent = getIntent();
	}
	
	/**
	 * 设置视图
	 */
	private void setViews()
	{
		this.cityTv.setText(CommonInfo.commonNowCityName);
	}
	
	/**
	 * 获取评论列表数据
	 */
	private void requestLocationData()
	{
		
		AsyncLoadData ald = new AsyncLoadData(mActivity, "定位中...", new AsyncAction()
		{
			
			@Override
			public void doLoad() throws Exception
			{
				addressObj = LocationUtil.queryLocation(mActivity, CommonInfo.commonLocation.getLatitude(),
						CommonInfo.commonLocation.getLongitude());
				
			}
			
			@Override
			public void loadEnd() throws Exception
			{
				addressTv.setText(addressObj.getProvince() + addressObj.getCity() + addressObj.getDistrict()
						+ addressObj.getStreet() + addressObj.getStreetNum());
				CommonInfo.commonLocationCityName = addressObj.getNowCity();
			}
			
		});
		ald.execute(0);
	}
	
	/**
	 * 获取商区列表数据
	 */
	private void requestAreaListData()
	{
		
		AsyncLoadData ald = new AsyncLoadData(mActivity, "", new AsyncAction()
		{
			
			@Override
			public void doLoad() throws Exception
			{
				// 获取提交参数
				Map<String, Object> addReviewParamMap = new HashMap<String, Object>();
				addReviewParamMap.put("cityName", CommonInfo.commonNowCityName);
				// 发送请求
				byte[] bAreaList = HttpUtil.requestByPost(mActivity, Constants.AREA_LIST_API, addReviewParamMap);
				if (bAreaList != null)
				{
					BaseActivity.areaList = new ParseJson().parseAreaListJson(bAreaList);
				}
				
			}
			
			@Override
			public void loadEnd() throws Exception
			{
				
			}
			
		});
		ald.execute(0);
	}
	
	/**
	 * 广播接收器
	 * 
	 * @author user
	 */
	private class MyReceiver extends BroadcastReceiver
	{
		
		@Override
		public void onReceive(Context context, Intent intent)
		{
			Bundle bundle = intent.getExtras();
			Double lon = bundle.getDouble("longitude");
			Double lat = bundle.getDouble("Latitude");
			if (CommonInfo.commonLocation != null)
			{
				CommonInfo.commonLocation.setLongitude(lon);
				CommonInfo.commonLocation.setLatitude(lat);
				requestLocationData();
			}
		}
	}
}
